//
//  HYQViewController.m
//  HYQImagePickerController
//
//  Created by zxj1989 on 08/27/2018.
//  Copyright (c) 2018 zxj1989. All rights reserved.
//

#import "HYQViewController.h"
#import "HYQTestCollectionViewCell.h"
#import "HYQImagePickerManager.h"
#import "UIView+Layout.h"

#import "TZPhotoPreviewController.h"
#import "TZImagePickerController.h"

@interface HYQViewController () <UICollectionViewDelegate,
                                UICollectionViewDataSource, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIButton *pickButton;
@property (nonatomic, strong) UIView *typeSelectView;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (nonatomic, strong) NSMutableArray *selectedAssets;

@property (nonatomic, assign) HYQImagePickerType currentPickerType;
@property (nonatomic, assign) BOOL needCrop;
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;
@property (nonatomic, assign) BOOL isSelectedVideo;
@property (nonatomic, strong) HYQImagePickerManager *picker;
@property (nonatomic, strong) UIImagePickerController *imagePicker;

@end

@implementation HYQViewController

- (UIButton *)pickButton
{
    if (!_pickButton) {
        _pickButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_pickButton setTitle:@"添加" forState:UIControlStateNormal];
        [_pickButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _pickButton.backgroundColor = [UIColor lightGrayColor];
        [_pickButton addTarget:self action:@selector(pickAction:) forControlEvents:UIControlEventTouchUpInside];
        _pickButton.frame = CGRectMake(10, 35, 100, 100);
    }
    return _pickButton;
}

- (UIView *)typeSelectView
{
    if (!_typeSelectView) {
        _typeSelectView = [[UIView alloc] initWithFrame:CGRectMake(120, 35, CGRectGetWidth(self.view.bounds) - 130, 100)];
        _typeSelectView.backgroundColor = [UIColor orangeColor];
        
        NSArray *types = @[@"图片单选",@"图片单选(裁剪)",@"视频单选",@"只可以选择图片(多选)",@"只可以选择视频",@"混合选择"];
        
        UIView *temp = nil;
        for (int i = 0; i < types.count; i ++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.titleLabel.font = [UIFont systemFontOfSize:12];
            btn.titleLabel.adjustsFontSizeToFitWidth = YES;
            [btn setTitle:types[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn.layer.borderColor = [UIColor whiteColor].CGColor;
            btn.layer.borderWidth = 0.5f;
            btn.tag = 100 + i;
            btn.selected = i == 0;
            CGFloat x = 5;
            CGFloat y = 5;
            CGFloat w = 100;
            CGFloat h = 25;
            if (temp) {
                if (temp.tz_right + w + 10 > _typeSelectView.tz_width) {
                    x = 5;
                    y = temp.tz_bottom + 5;
                }else {
                    x = temp.tz_right + 5;
                    y = temp.tz_top;
                }
            }
            btn.frame = CGRectMake(x, y, w, h);
            temp = btn;
            [_typeSelectView addSubview:btn];
            [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return _typeSelectView;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width = floor((CGRectGetWidth([[UIScreen mainScreen] bounds]) - 50) / 3.0);
        flowLayout.itemSize = CGSizeMake(width, width);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = 10;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 215, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight([[UIScreen mainScreen] bounds])) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[HYQTestCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([HYQTestCollectionViewCell class])];
    }
    return _collectionView;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _imagePicker;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.pickButton];
    [self.view addSubview:self.typeSelectView];
    [self.view addSubview:self.collectionView];
    
    UIAlertController *controller = [[UIAlertController alertControllerWithTitle:@"无法访问相机" message:@"相机不可用" preferredStyle:UIAlertControllerStyleAlert] init];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [controller addAction:action1];
    [self presentViewController:controller animated:YES completion:NULL];
}

- (void)btnAction:(UIButton *)btn
{
    if (btn.selected) {
        return;
    }
    for (UIButton *button in self.typeSelectView.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            button.selected = NO;
        }
    }
    btn.selected = YES;
    self.needCrop = btn.tag == 101;
    HYQImagePickerType type = self.currentPickerType = btn.tag - 101;
    if (btn.tag - 100 < 1) {
        type = HYQImagePickerTypeOnlyPhoto;
    }
    self.currentPickerType = type;
    [self.selectedPhotos removeAllObjects];
    [self.selectedAssets removeAllObjects];
    self.isSelectOriginalPhoto = NO;
    [self.collectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.selectedPhotos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HYQTestCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HYQTestCollectionViewCell" forIndexPath:indexPath];
    cell.imageView.image = self.selectedPhotos[indexPath.item];
    cell.delButton.tag = indexPath.item + 100;
    [cell.delButton addTarget:self action:@selector(delAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSelectedVideo) {
        [self previewVideo];
    }else {
        [self previewImagesAtIndex:indexPath.item];
    }
}

- (void)delAction:(UIButton *)btn
{
    [self.selectedAssets removeObjectAtIndex:btn.tag - 100];
    [self.selectedPhotos removeObjectAtIndex:btn.tag - 100];
    [self.collectionView reloadData];
}

- (void)pickAction:(UIButton *)pickAction
{
    self.picker = [[HYQImagePickerManager alloc] initPickerWithType:self.currentPickerType];
    self.picker.sceneViewController = self;
    self.picker.needCrop = self.needCrop;
    self.picker.cropScale = 1;
    self.picker.selectedAssets = self.selectedAssets;
    self.picker.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
    __weak typeof(&*self) weakSelf = self;
    self.picker.didPickPhotosBlock = ^(NSArray *selectedAssets, NSArray *thumbImages, BOOL isSelectOriginalPhoto) {
        weakSelf.isSelectedVideo = NO;
        weakSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:thumbImages];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:selectedAssets];
        [weakSelf.collectionView reloadData];
    };
    self.picker.didPickCropPhotoBlock = ^(PHAsset *asset, UIImage *cropImage) {
        weakSelf.isSelectedVideo = NO;
        weakSelf.isSelectOriginalPhoto = NO;
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:@[cropImage]];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
        [weakSelf.collectionView reloadData];
    };
    self.picker.didPickVideoBlock = ^(PHAsset *asset, UIImage *coverImage) {
        weakSelf.isSelectedVideo = YES;
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
        [weakSelf.collectionView reloadData];
    };
    [self.picker showImagePickerAnimated:NO];
}

- (void)testTakePhotoAndCrop
{
    self.picker = [[HYQImagePickerManager alloc] initWithTakePhotoViewController];
    self.picker.needCrop = YES;
    self.picker.cropScale = 1;
    self.picker.sceneViewController = self;
    self.picker.didPickCropPhotoBlock = ^(PHAsset *asset, UIImage *cropImage) {
        
    };
    [self.picker showImagePickerAnimated:YES];
}

- (void)previewImagesAtIndex:(NSInteger)index
{
    self.picker = [[HYQImagePickerManager alloc] initPreviewPhotoPickerWithType:self.currentPickerType selectedAssets:self.selectedAssets selectedPhotos:self.selectedPhotos currentIndex:index];
    self.picker.sceneViewController = self;
    self.picker.isAllowSelectOriginalPhoto = !(self.currentPickerType == HYQImagePickerTypeSinglePhoto && self.needCrop == YES);
    self.picker.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
    __weak typeof(&*self) weakSelf = self;
    self.picker.didPickPhotosBlock = ^(NSArray *selectedAssets, NSArray *thumbImages, BOOL isSelectOriginalPhoto) {
        weakSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:thumbImages];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:selectedAssets];
        [weakSelf.collectionView reloadData];
    };
    [self.picker showImagePickerAnimated:YES];
}

- (void)previewVideo
{
    self.picker = [[HYQImagePickerManager alloc] initPreviewVideoControllerWithAsset:[self.selectedAssets firstObject]];
    self.picker.sceneViewController = self;
    [self.picker showImagePickerAnimated:YES];
}

- (void)cropImage
{
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [[TZImageManager manager] savePhotoWithImage:info[UIImagePickerControllerOriginalImage] completion:^(PHAsset *asset, NSError *error) {
       TZImagePickerController *tzpicer = [[TZImagePickerController alloc] initCropTypeWithAsset:asset photo:info[UIImagePickerControllerOriginalImage] completion:^(UIImage *cropImage, PHAsset *asset) {
            
        }];
        [self presentViewController:tzpicer animated:YES completion:NULL];
    }];
    
    [picker dismissViewControllerAnimated:NO completion:NULL];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo
{
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
